package servlet;

import pojo.User;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

@WebServlet(urlPatterns = "/add")
public class AddUserServlet extends HttpServlet {

    private static final Logger logger = Logger.getLogger(AddUserServlet.class.getName());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            processRequest(req, resp);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Error processing request", e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while processing the request.");
        }
    }

    private void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 编码处理 解决汉字传递乱码
        req.setCharacterEncoding("utf-8");

        // 获取页面传递的参数
        String name = req.getParameter("name");
        String pass = req.getParameter("pass");

        // 验证参数是否为空
        if (name == null || name.trim().isEmpty() || pass == null || pass.trim().isEmpty()) {
            logger.log(Level.WARNING, "Missing required parameters: name or pass");
            resp.sendRedirect("addUser.jsp?error=missingParameters");
            return;
        }

        // 调用服务层方法添加用户
        UserService userService = new UserServiceImpl();
        int result = userService.addUser(new User(name, pass));

        // 根据结果进行重定向
        if (result > 0) {
            // 添加成功，重定向到用户列表页面
            resp.sendRedirect("user");
        } else {
            // 添加失败，重定向回添加用户页面
            resp.sendRedirect("addUser.jsp?error=addFailed");
        }
    }
}
